<script setup>
import { ref } from 'vue';
import {
  ElMessage,
  ElUpload,
  ElButton,
  ElInput,
  ElSelect,
  ElOption,
  ElInputNumber,
  ElForm,
  ElFormItem,
  ElCard,
  ElIcon,
  ElDivider, // 引入分割线组件
} from 'element-plus';
import { UploadFilled, Plus } from '@element-plus/icons-vue';

import resourceService from '@/services/resourceService.js';
import { useRouter } from 'vue-router';
import { userManager } from "@/utils/user.js";

const router = useRouter();

// --- 文件上传相关数据 ---
const mainFileUploadRef = ref(null);
const fileList = ref([]);
const uploadedRawFile = ref(null);

const coverImageUploadRef = ref(null);
const coverImageList = ref([]);
const uploadedRawCoverImage = ref(null);

const resourceTitle = ref('');
const resourceCategory = ref(null);
const resourceMajor = ref(null);
const resourceDifficulty = ref(null);
const resourceCredit = ref(null);
const uploading = ref(false);

// 类别选项数据
const categoryOptions = [
  { label: 'PPT', value: 0 },
  { label: '视频(仅支持MP4）', value: 1 },
  { label: '图片', value: 2 },
  { label: 'Word', value: 3 },
  { label: 'Zip', value: 4 },
  { label: 'Excel', value: 5 },
  { label: '其他', value: 6 },
];

// 难度选项数据
const difficultyOptions = [
  { label: '入门', value: 0},
  { label: '初级', value: 1 },
  { label: '中级', value: 2 },
  { label: '高级', value: 3 },
];

const majorOptions = ref([
  '哲学','经济学','金融学','法学','马克思主义理论','教育学','体育',
  '文学','历史学','数学','物理学','化学','天文学','地理学','力学类','机械',
  '材料','能源类','电气','自动化','计算机','电子信息','矿业','土木水利',
  '农学','医学','药学','管理学','艺术类'
]);

// --- 主要文件上传处理 ---
const handleMainFileUploadChange = (uploadFile) => {
  if (uploadFile.status === 'ready' || uploadFile.status === 'success') {
    uploadedRawFile.value = uploadFile.raw;
    fileList.value = [uploadFile];
  } else if (uploadFile.status === 'fail' || uploadFile.status === 'abort') {
    ElMessage.error({ message: `文件 ${uploadFile.name} 上传失败！`, offset: 80 });
    uploadedRawFile.value = null;
    fileList.value = [];
    if (mainFileUploadRef.value) {
      mainFileUploadRef.value.clearFiles();
    }
  }
};

const handleMainFileUploadRemove = (uploadFile) => {
  uploadedRawFile.value = null;
  fileList.value = [];
  ElMessage.info({ message: `文件 ${uploadFile.name} 已移除`, offset: 80 });
};

// --- 封面图片上传处理 ---
const handleCoverImageUploadChange = (uploadFile, uploadFiles) => {
  if (uploadFiles.length > 1 && uploadFile.status !== 'removed') {
    const oldFiles = uploadFiles.filter(f => f.uid !== uploadFile.uid);
    if (coverImageUploadRef.value) {
      oldFiles.forEach(f => coverImageUploadRef.value.handleRemove(f));
    }
    coverImageList.value = [uploadFile];
    uploadedRawCoverImage.value = uploadFile.raw;
  } else if (uploadFile.status === 'ready' || uploadFile.status === 'success') {
    uploadedRawCoverImage.value = uploadFile.raw;
    coverImageList.value = [uploadFile];
  } else if (uploadFile.status === 'fail' || uploadFile.status === 'abort') {
    ElMessage.error({message: `封面图片 ${uploadFile.name} 上传失败！`, offset: 80});
    uploadedRawCoverImage.value = null;
    coverImageList.value = [];
  }
};

const handleCoverImageUploadRemove = (uploadFile) => {
  uploadedRawCoverImage.value = null;
  coverImageList.value = [];
  ElMessage.info({message: `封面图片 ${uploadFile.name} 已移除`, offset: 80});
};

// 提交上传
const submitUpload = async () => {
  if (!uploadedRawFile.value) {
    ElMessage.warning({message: '请选择要上传的资源文件！', offset: 80});
    return;
  }
  if (uploadedRawFile.value.size === 0) {
    ElMessage.warning({message: '选中的资源文件为空或无效，请重新选择！', offset: 80});
    uploadedRawFile.value = null;
    if (mainFileUploadRef.value) {
      mainFileUploadRef.value.clearFiles();
    }
    return;
  }
  if (!uploadedRawCoverImage.value) {
    ElMessage.warning({message: '请上传资源封面图片！', offset: 80});
    return;
  }
  if (!resourceTitle.value) {
    ElMessage.warning({message: '请输入资源标题！', offset: 80});
    return;
  }
  if (resourceCategory.value === null) {
    ElMessage.warning({message: '请选择资源类别！', offset: 80});
    return;
  }

  const publisherId = userManager.getUserId();
  if (!publisherId) {
    ElMessage.error({message: '无法获取用户ID，请先登录！', offset: 80});
    return;
  }

  uploading.value = true;

  const formData = new FormData();
  formData.append('file', uploadedRawFile.value);
  if (uploadedRawCoverImage.value) {
    formData.append('coverImage', uploadedRawCoverImage.value);
  }

  const resourceMetadata = {
    title: resourceTitle.value,
    category: resourceCategory.value,
    major: resourceMajor.value,
    difficulty: resourceDifficulty.value,
    credit: resourceCredit.value,
    publisherId: publisherId,
  };
  formData.append('resource', new Blob([JSON.stringify(resourceMetadata)], {type: 'application/json'}));

  try {
    const response = await resourceService.createResource(formData);
    if (response.success) {
      ElMessage.success({message: '文件上传成功并创建资源！', offset: 80});
      resetForm();
      router.push('/');
    } else {
      ElMessage.error({message: '文件上传失败：' + (response.message || '服务器响应异常'), offset: 80});
    }
  } catch (error) {
    console.error('上传过程中发生错误:', error);
    if (error.response && error.response.data && error.response.data.message) {
      ElMessage.error({message: '上传过程中发生错误：' + error.response.data.message, offset: 80});
    } else {
      ElMessage.error({message: '网络错误或服务器无响应，请稍后再试！', offset: 80});
    }
  } finally {
    uploading.value = false;
  }
};

// 重置表单
const resetForm = () => {
  uploadedRawFile.value = null;
  fileList.value = [];
  if (mainFileUploadRef.value) {
    mainFileUploadRef.value.clearFiles();
  }
  uploadedRawCoverImage.value = null;
  coverImageList.value = [];
  if (coverImageUploadRef.value) {
    coverImageUploadRef.value.clearFiles();
  }
  resourceTitle.value = '';
  resourceCategory.value = null;
  resourceMajor.value = null;
  resourceDifficulty.value = null;
  resourceCredit.value = null;
};

// --- 返回主页 ---
const goBack = () => {
  router.push('/');
};
</script>

<template>
  <div class="resource-upload-page-container">
    <div class="main-upload-content">
      <el-card class="page-header-card" shadow="never">
        <div class="page-header-content">
          <h2>上传新的学习资源</h2>
          <p>分享知识，共筑未来学习社区</p>
        </div>
      </el-card>

      <el-card class="unified-form-card" shadow="never">
        <div class="form-section-title">第一步：上传核心文件</div>
        <el-upload
            ref="mainFileUploadRef"
            drag
            :auto-upload="false"
            :limit="1"
            accept="*"
            :file-list="fileList"
            :on-change="handleMainFileUploadChange"
            :on-remove="handleMainFileUploadRemove"
            class="main-file-upload"
            list-type="text"
        >
          <el-icon class="el-icon--upload-filled">
            <upload-filled/>
          </el-icon>
          <div class="el-upload__text">将文件拖到此处，或 <em>点击选择文件</em></div>
          <template #tip>
            <div class="el-upload__tip">支持任意文件类型，单个文件大小不超过 100MB</div>
          </template>
        </el-upload>

        <el-divider class="section-divider"/>

        <div class="form-section-title">第二步：完善资源信息</div>
        <el-form label-width="100px" class="resource-info-form" label-position="right">
          <el-form-item label="资源标题" required>
            <el-input v-model="resourceTitle" placeholder="为您的资源起一个清晰的标题"></el-input>
          </el-form-item>

          <el-form-item label="封面图片" required>
            <el-upload
                ref="coverImageUploadRef"
                action="#"
                list-type="picture-card"
                :auto-upload="false"
                :limit="1"
                accept="image/*"
                :file-list="coverImageList"
                :on-change="handleCoverImageUploadChange"
                :on-remove="handleCoverImageUploadRemove"
                class="cover-image-uploader"
            >
              <el-icon><Plus/></el-icon>
              <template #tip>
                <div class="el-upload__tip">上传一张吸引人的封面吧</div>
              </template>
            </el-upload>
          </el-form-item>

          <el-form-item label="资源类别" required>
            <el-select v-model="resourceCategory" placeholder="请选择资源类别" class="full-width-input">
              <el-option
                  v-for="item in categoryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="所属专业">
            <el-select v-model="resourceMajor" placeholder="选填，精准匹配给需要的同学" class="full-width-input" filterable>
              <el-option
                  v-for="item in majorOptions"
                  :key="item"
                  :label="item"
                  :value="item"
                  class="dense-option"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="难度等级">
            <el-select v-model="resourceDifficulty" placeholder="选填，帮助他人了解资源深度" class="full-width-input">
              <el-option
                  v-for="item in difficultyOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="所需学分">
            <el-input-number
                v-model="resourceCredit"
                :min="0"
                :max="100"
                controls-position="right"
                placeholder="0"
                class="full-width-input align-left-input-number"
            ></el-input-number>
          </el-form-item>
        </el-form>

        <div class="action-buttons">
          <el-button @click="goBack" size="large">返 回</el-button>
          <el-button type="primary" :loading="uploading" @click="submitUpload" size="large">
            {{ uploading ? '正在上传...' : '确认并发布资源' }}
          </el-button>
        </div>
      </el-card>

    </div>
  </div>
</template>

<style scoped>
/* 页面背景和通用布局 */
.resource-upload-page-container {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding: 24px;
  box-sizing: border-box;
}

/* 主内容区 */
.main-upload-content {
  max-width: 960px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  gap: 24px;
}

/* 头部卡片 */
.page-header-card {
  background-color: var(--el-color-primary);
  color: white;
  text-align: center;
  border-radius: 12px;
  padding: 32px 20px;
  border: none;
}
.page-header-card h2 {
  font-size: 28px;
  margin-bottom: 8px;
  font-weight: 600;
}
.page-header-card p {
  font-size: 16px;
  opacity: 0.9;
  font-weight: 300;
}

/* 统一的表单卡片样式 */
.unified-form-card {
  border-radius: 12px;
  border: 1px solid #e4e7ed;
  padding: 16px 24px; /* 调整内边距 */
}

/* 区段标题样式 */
.form-section-title {
  font-size: 18px;
  color: #303133;
  font-weight: 600;
  margin-bottom: 24px;
}

/* 分割线样式 */
.section-divider {
  margin: 32px 0; /* 增加分割线上下的间距 */
}

/* --- 主要文件上传区 ElUpload --- */
.main-file-upload {
  margin-bottom: 16px; /* 为上传组件底部增加一些间距 */
}
.main-file-upload :deep(.el-upload-dragger) {
  width: 100%;
  height: 180px; /* 略微减小高度 */
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  background-color: #fafafa;
  transition: border-color 0.3s, background-color 0.3s;
}
.main-file-upload :deep(.el-upload-dragger):hover {
  border-color: var(--el-color-primary);
  background-color: #ecf5ff;
}
.main-file-upload :deep(.el-icon--upload-filled) {
  font-size: 56px;
  color: #c0c4cc;
  margin-bottom: 16px;
  transition: color 0.3s;
}
.main-file-upload :deep(.el-upload-dragger):hover .el-icon--upload-filled {
  color: var(--el-color-primary);
}
.main-file-upload :deep(.el-upload__text) {
  font-size: 16px;
  color: #606266;
}
.main-file-upload :deep(.el-upload__text em) {
  color: var(--el-color-primary);
  font-style: normal;
}
.main-file-upload :deep(.el-upload__tip) {
  font-size: 13px;
  color: #909399;
  margin-top: 12px;
  text-align: center;
}
/* ElUpload 文件列表样式 */
.main-file-upload :deep(.el-upload-list__item) {
  background-color: #f4f4f5;
  border: 1px solid #e9e9eb;
  border-radius: 4px;
  padding: 8px 12px;
  transition: all 0.2s;
}
.main-file-upload :deep(.el-upload-list__item:hover) {
  background-color: #ecf5ff;
  border-color: var(--el-color-primary-light-7);
}


/* --- 资源基本信息表单 --- */
.resource-info-form .el-form-item {
  margin-bottom: 22px;
}
.resource-info-form :deep(.el-form-item__label) {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}
/* 必填星号颜色 */
.resource-info-form :deep(.el-form-item.is-required:not(.is-no-required-mark) > .el-form-item__label-wrap > .el-form-item__label:before),
.resource-info-form :deep(.el-form-item.is-required:not(.is-no-required-mark) > .el-form-item__label:before) {
  color: var(--el-color-danger);
}
.full-width-input {
  width: 100%;
}
/* 优化 select 选项密度 */
.el-select-dropdown__item.dense-option {
  padding-top: 5px;
  padding-bottom: 5px;
  line-height: 1.2;
  font-size: 13px;
}
/* 学分输入框 */
.align-left-input-number :deep(.el-input__inner) {
  text-align: left !important;
}

/* --- 封面图片上传组件 --- */
.cover-image-uploader :deep(.el-upload--picture-card) {
  width: 148px;
  height: 148px;
  border-radius: 8px;
}
.cover-image-uploader :deep(.el-upload-list__item) {
  width: 148px;
  height: 148px;
  border-radius: 8px;
}
.cover-image-uploader :deep(.el-upload__tip) {
  font-size: 13px;
  color: #909399;
  margin-top: 0;
}

/* --- 按钮 --- */
.action-buttons {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 24px;
  padding-top: 24px;
  border-top: 1px solid #e4e7ed;
}
.action-buttons .el-button {
  width: 160px;
}


/* 响应式调整 */
@media (max-width: 768px) {
  .resource-upload-page-container {
    padding: 16px;
  }
  .main-upload-content {
    max-width: 100%;
    gap: 16px;
  }
  .page-header-card h2 {
    font-size: 22px;
  }
  .page-header-card p {
    font-size: 14px;
  }
  .main-file-upload :deep(.el-upload-dragger) {
    height: 160px;
  }
  .action-buttons {
    flex-direction: column;
    align-items: stretch;
  }
  .action-buttons .el-button {
    width: 100%;
  }
  .cover-image-uploader :deep(.el-upload--picture-card),
  .cover-image-uploader :deep(.el-upload-list__item) {
    width: 120px;
    height: 120px;
  }
}
</style>